<template>
  <div class="table_list_fix">
    <!-- 扩展性内容 -->
    <slot name="content_context" class="content_context" />
    <!-- table表格 -->
    <el-table
      class="basic-table"
      use-virtual
      ref="elTable"
      v-loading="loading"
      :border="border"
      :data="dataSource"
      :height="tableHeight"
      :max-height="maxTableHeight"
      :show-summary="showSummary"
      :show-header="showHeader"
      :header-cell-style="{ textAlign: 'center' }"
      @header-dragend="handleHeaderDragend"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDblclick"
      :summary-method="getSummaries"
      :span-method="spanMethod"
      :row-style="{height: '40px'}"
      @sort-change="handleSortChange"
    >
      <el-table-column v-if="showSelectCol" fixed type="selection" width="55" :selectable="handleSelectable" />
      <template v-for="(column, key) in columns">
        <el-table-column
          v-if="!column.children"
          :key="key"
          :prop="column.key"
          :label="column.title"
          :property="column.key"
          :align="column.align || 'center'"
          :width="column.fixedWidth"
          :min-width="column.width || defaultWidth"
          :fixed="column.fixed"
          :formatter="column.formatter"
          :show-overflow-tooltip="isShowTooltip"
          :sortable="column.sortable"
        >
          <template v-if="column.render" v-slot="scope">
            <table-column
              :index="scope.$index"
              :row="scope.row"
              :col="scope.column"
              :render="column.render"
            />
          </template>
        </el-table-column>
        <el-table-column
          v-else
          :key="key"
          :label="column.title"
          :show-overflow-tooltip="true"
        >
          <el-table-column
            v-for="child in column.children"
            :key="child.key"
            :prop="child.key"
            :label="child.title"
            :property="child.key"
            :align="child.align || 'center'"
            :width="child.fixedWidth"
            :min-width="child.width || childDefaultWidth"
            :formatter="child.formatter"
            :show-overflow-tooltip="true"
          >
            <template v-if="child.render" v-slot="scope">
              <table-column
                :index="scope.$index"
                :row="scope.row"
                :col="scope.column"
                :render="child.render"
              />
            </template>
          </el-table-column>
        </el-table-column>
      </template>
      <el-table-column
        align="center"
        v-if="showActionCol"
        :fixed="actionColFixed"
        :min-width="actionColWidth"
        :label="actionColLabel">
        <template slot-scope="scope">
          <table-column
            :index="scope.$index"
            :row="scope.row"
            :col="scope.column"
            :render="actionRender"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页部分 -->
    <div v-if="showPagination" class="pagination-container">
      <el-pagination
        :total="pagination.total"
        :current-page="pagination.current || pagination.pageNum"
        :page-sizes="pageSizes"
        :page-size="pagination.size || pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<script>
import tableColumn from './tableColumn';
import { toFixedCustomize } from '@/utils/bizUtils'

export default {
  name: 'BasicList',
  components: {
    tableColumn,
  },
  props: {
    dataSource: {
      type: Array,
      default () {
        return [];
      },
    },
    columns: {
      type: Array,
      default () {
        return [];
      },
    },
    actionColFixed: {
      type: [Boolean, String],
      default: 'right',
    },
    showActionCol: {
      type: Boolean,
      default: false,
    },
    showSummary: {
      type: Boolean,
      default: false,
    },
    showHeader: {
      type: Boolean,
      default: true,
    },
    tableHeight: {
      type: Number,
      default: null,
    },
    maxTableHeight: {
      type: Number,
      default: null,
    },
    actionColWidth: {
      type: Number,
      default: 100,
    },
    actionColLabel: {
      type: String,
      default: '操作',
    },
    actionRender: {
      type: Function,
      default: () => {},
    },
    showSelectCol: {
      type: Boolean,
      default: true,
    },
    border: {
      type: Boolean,
      default: true,
    },
    loading: {
      type: Boolean,
      default: false,
    },
    showPagination: {
      type: Boolean,
      default: true,
    },
    pagination: {
      type: Object,
      default () {
        return {
          current: 1,
          total: 0,
          size: 10,
        }
      },
    },
    pageSizes: {
      type: Array,
      default () {
        return [10, 50, 100, 200]
      }
    },
    selectionChange: {
      type: Function,
      default: () => {},
    },
    spanMethod: {
      type: Function,
      default: () => {},
    },
    isShowTooltip: {
      type: Boolean,
      default: true
    },
    checkSelectable: {
      type: Function
    },
    // 合计字段
    summaryFields: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 一级表头列宽
    defaultWidth: {
      typeof: Number,
      default: 120
    },
    // 二级表头列宽
    childDefaultWidth: {
      typeof: Number,
      default: 120
    }
  },

  data () {
    return {
      multipleSelection: [],
    };
  },
  watch: {
    dataSource: {
      handler (newVal) {
        if (this.$refs.elTable) {
          this.$nextTick(() => {
            this.$refs.elTable.doLayout();
          })
        }
      },
      immediate: true,
      deep: true
    },
    columns: {
      handler (newVal) {
        if (this.$refs.elTable) {
          this.$nextTick(() => {
            this.$refs.elTable.doLayout();
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.$emit('toggleRowSelection', this.$refs.multipleTable);
    });
  },
  methods: {
    handleHeaderDragend () {
      this.$nextTick(() => {
        this.$refs.elTable.doLayout();
      });
    },
    handlePageChange (current) {
      this.$emit('pageChange', current);
    },
    handlePageSizeChange (length) {
      this.$emit('pageSizeChange', length);
    },
    handleRowDblclick (row, column, event) {
      this.$emit('rowDblclick', row);
    },
    handleSelectionChange (rows) {
      console.log('handleSelectionChange :>> ', rows);
      this.selectionChange(rows)
      this.multipleSelection = rows
    },
    /* 表格checkbox禁用与否状态 */
    handleSelectable (row, index) {
      /*
        返回true，表格可勾选
        返回false，表格不可勾选
      */
      if (!this.checkSelectable) { // 如果没有表格勾选状态判断方法，就默认可以勾选
        return true;
      }
      return this.checkSelectable({ row, selections: this.multipleSelection });
    },
    // 自定义需合计字段
    getSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        this.summaryFields && this.summaryFields.map((ele) => {
          if (column.property.includes(ele)) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = toFixedCustomize(sums[index]);
          }
        })
      });
      return sums;
    },
    handleSortChange ({ prop, order }) {
      this.$emit('handleSortChange', { prop, order })
    }
  },
};
</script>

<style lang="less" scoped>
.basic-table {
  margin-top: 6px;
  /deep/.el-button {
    padding: 0px;
  }
}
/deep/.el-table thead.is-group th {
  background: #fff;
}
.operate-group {
  .operate-btn {
    margin-left: 5px;
  }
}
.pagination-container {
  text-align: right;
  padding-right: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.total-num {
  margin-top: 5px;
  float: right;
}
/deep/i.el-icon-plus {
  color: #fff;
  background-color: #2c68ff;
  padding: 2px;
  font-weight: 900;
}
</style>
